/*
* 工程大屏
*/
public without sharing class EngineerBigScrenUtil {
   	public  EngineerBigScrenUtil(){

    }
	@RemoteAction
	public static Map<String,Object> getData(String tag ){
		Map<String,Object> data = new Map<String,Object>();
			//获取当年年度回访次数
		data.put('feedBackCount', getFeedBackCount());	


  		//获取全年整体服务满意度
		data.put('satisfiyRito', getSatisfiyRito());  
    		//按月获取回访次数和服务满意度 取近半年的数据
		data.put('satisfiyRitoByMonth', getSaticfiyRitoAndCountByMonth()); 
    	//各省服务人员情况:用户部门 等于 客户服务中心(工程部),客户服务中心(产品培训部) 	
		data.put('servicePerson', getServicePerson());
		//自产仪器分布
		data.put('equipment', getEquipmentMap(tag));
		//工程工单统计
		data.put('workorderEngineer', getWorkOrderEnginnerMap());

		//产培工单统计
		data.put('workorderProduct', getWorkOrderProductMap());
		//获取工单总量 及同比

		data.put('workorderTotal', getWorkOrderTotal(tag));
		//获取服务计划完成情况
		data.put('serviceplan', getServicePlan(tag));

		//获取超时工单
		data.put('workorderTimeOut', getWorkOrderTimeOut(tag ));

		return data ;
	}
	//获取当年年度回访次数
    public static Integer getFeedBackCount(){
		Datetime d =  Datetime.newInstance(System.today().year(),1,1,0,0,0);
    	return [select count() from FeedBack__c where  (not Account__r.Name like '%迈克测试%') and CreatedDate >=:d ];
    }
    //获取全年整体服务满意度
    public static Decimal getSatisfiyRito(){

    	Datetime d =  Datetime.newInstance(System.today().year(),1,1,0,0,0);
		Decimal t = [select count() from FeedBack__c where  (not Account__r.Name like '%迈克测试%') and CreatedDate >=:d and  SatisfactionDegree__c != null ];

		Decimal m = [select count() from FeedBack__c where  
		              (not Account__r.Name like '%迈克测试%') 
		              and CreatedDate >:d 
		              and SatisfactionDegree__c in ('满意','非常满意')  ];
		
		return  t == 0 ? 0 : m/t  ;
    }
    //按月获取回访次数和服务满意度 取近半年的数据
    public static Object  getSaticfiyRitoAndCountByMonth(){

    	Date month6 = System.today().addMonths(-6);
    	//Datetime d =  DateTime.newInstance(month6.year(),month6.month(),1,0,0,0);
    	Date d =  Date.newInstance(month6.year(),month6.month(),1);

    	Map<String ,String> feadBackCountMap= new Map<String,String>();
    	//回访次数
    	for(AggregateResult arg :[select count(Id) total,calendar_year(Returnvisitschedule__c) year ,calendar_month(Returnvisitschedule__c) month from FeedBack__c 
              where  (not Account__r.Name like '%迈克测试%') 
              and Returnvisitschedule__c >=:d 
              group by calendar_year(Returnvisitschedule__c)   ,calendar_month(Returnvisitschedule__c) order by calendar_year(Returnvisitschedule__c)
             ]){
    		feadBackCountMap.put(String.valueOf(arg.get('month'))+'月',String.valueOf(arg.get('total')));
			//System.debug( arg.get('year')+'年'+arg.get('month')+'月==>'+ arg.get('total') );
		}


		//服务满意度
		//排除物流回访 
    	Map<String ,Decimal> serviceCountMap= new Map<String,Decimal>();
		for(AggregateResult arg : [select count(Id) total ,calendar_year(Returnvisitschedule__c) year ,calendar_month(Returnvisitschedule__c) month  from FeedBack__c
			 where  (not Account__r.Name like '%迈克测试%') 
			and Returnvisitschedule__c >=:d and  SatisfactionDegree__c != null
			group by calendar_year(Returnvisitschedule__c)  ,calendar_month(Returnvisitschedule__c) order by calendar_year(Returnvisitschedule__c) ]){

    		serviceCountMap.put(String.valueOf(arg.get('month'))+'月',Decimal.valueOf(String.valueOf(arg.get('total'))) );

		}

		Map<String ,Decimal> serviceSatisCountMap= new Map<String,Decimal>();
		

		for(AggregateResult arg : [select count(Id) total ,calendar_year(Returnvisitschedule__c) year ,calendar_month(Returnvisitschedule__c) month  from FeedBack__c
			 where  (not Account__r.Name like '%迈克测试%') 
			and Returnvisitschedule__c >=:d and   SatisfactionDegree__c in ('满意','非常满意')
			group by calendar_year(Returnvisitschedule__c)   ,calendar_month(Returnvisitschedule__c) order by calendar_year(Returnvisitschedule__c) ]){

    		serviceSatisCountMap.put(String.valueOf(arg.get('month'))+'月',Decimal.valueOf(String.valueOf(arg.get('total'))) );

		}


		Map<String,Decimal> resMap = new Map<String,Decimal>();
		for(String mon : serviceCountMap.keyset() ){

			if(serviceSatisCountMap.containsKey(mon)){
				resMap.put(mon, serviceSatisCountMap.get(mon) /  serviceCountMap.get(mon));
			}else{
				resMap.put(mon, 0 );

			}
		}

		Map<String,Object> rMap = new Map<String,Object>();
		rMap.put('satisfiyRito', resMap);
		rMap.put('feedCount', feadBackCountMap);

		//return JSON.deserializeUntyped('{"feedCount":{"9月":"341","8月":"1848","7月":"2031","6月":"1771","5月":"1940","4月":"2162","3月":"2105"},"satisfiyRito":{"8月":0.991769547325102880658436213991770,"7月":0.994897959183673469387755102040816,"6月":0.987878787878787878787878787878788,"5月":0.996015936254980079681274900398406,"4月":1,"3月":0.979112271540469973890339425587467}}');
		return rMap;

    }


    //各省服务人员情况:用户部门 等于 客户服务中心(工程部),客户服务中心(产品培训部) 	
    public static Object getServicePerson(){
    	Map<String,Map<String,Object>> resMap = new Map<String,Map<String,Object>>();
    	 List <Report> reportList = [SELECT Id,DeveloperName FROM Report where
	    DeveloperName = 'TP_Users'];
		String reportId = (String)reportList.get(0).get('Id');
		Reports.reportResults results = Reports.ReportManager.runReport(reportId, true);
	
		Reports.Dimension dim = results.getGroupingsDown();

		Reports.Dimension cols = results.getGroupingsAcross();

	   for(Reports.GroupingValue groupingVal : dim.getGroupings()  ){
           
        	
           
           //子公司大区
            /*Reports.ReportFactWithDetails factDetails =
                (Reports.ReportFactWithDetails)results.getFactMap().get(groupingVal.getKey() + '!T');
           Object value = factDetails.getAggregates()[0].getValue();*/
           Map<String,Object> tmp = new Map<String,Object>();

           for(Reports.GroupingValue col : cols.getGroupings() ){

           		  Reports.ReportFactWithDetails factcpb  =
	                (Reports.ReportFactWithDetails)results.getFactMap().get(groupingVal.getKey() + '!'+col.getKey());
	           Object factcpbvalue = factcpb.getAggregates()[0].getValue();
	           tmp.put(col.getLabel(), factcpbvalue);

           }
           //产培
            
           //工程
           /* Reports.ReportFactWithDetails factgcb  =
                (Reports.ReportFactWithDetails)results.getFactMap().get(groupingVal.getKey() + '!0');
           Object factgcbvalue = factgcb.getAggregates()[0].getValue();
      		 tmp.put('gcb', factgcbvalue);
           System.debug(groupingVal.getValue() +'==>'+value + ' = '+factcpbvalue+' + '+factgcbvalue );*/
            resMap.put(String.valueOf(groupingVal.getValue()), tmp);
       
       }

      	//return JSON.deserializeUntyped('{"重庆征途":{"客户服务中心(产品培训部)":7,"客户服务中心(工程部)":21},"迈克实业":{"客户服务中心(产品培训部)":16,"客户服务中心(工程部)":64},"贵州迈克":{"客户服务中心(产品培训部)":2,"客户服务中心(工程部)":15},"西北":{"客户服务中心(产品培训部)":4,"客户服务中心(工程部)":6},"湖北迈克":{"客户服务中心(产品培训部)":2,"客户服务中心(工程部)":6},"新疆迈克":{"客户服务中心(产品培训部)":4,"客户服务中心(工程部)":6},"广东迈克":{"客户服务中心(产品培训部)":2,"客户服务中心(工程部)":13},"山西迈克":{"客户服务中心(产品培训部)":2,"客户服务中心(工程部)":10},"山东迈克":{"客户服务中心(产品培训部)":5,"客户服务中心(工程部)":16},"吉林迈克":{"客户服务中心(产品培训部)":4,"客户服务中心(工程部)":20},"华南":{"客户服务中心(产品培训部)":1,"客户服务中心(工程部)":9},"华北":{"客户服务中心(产品培训部)":2,"客户服务中心(工程部)":2},"华中":{"客户服务中心(产品培训部)":5,"客户服务中心(工程部)":16},"北京迈克":{"客户服务中心(产品培训部)":4,"客户服务中心(工程部)":18},"内蒙迈克":{"客户服务中心(产品培训部)":6,"客户服务中心(工程部)":18},"云南迈克":{"客户服务中心(产品培训部)":3,"客户服务中心(工程部)":16},"上海迈可优":{"客户服务中心(产品培训部)":5,"客户服务中心(工程部)":14}}');
 		return resMap;


    }
    /*

	筛选依据：					
   	显示: 全部客户				
   	客户名 不包含 迈克测试 				
   	AND 品牌 包含 迈克,加斯戴克,深圳爱康 				
   	AND 产品: 存货编码 不等于 100020100002,100030500001,301532200101,301532200102,301532200103,301532200104,301532200105,301532200100,300393000400,100090100002,8000303FR002,8000303RU002,800030300002,100030300001,100030300002,100040100003,100040100004,100040100005,100040100006,100040100007,100040100008,100040100009,100040100010,100040100001,100040100002,100020300001,800100100003,800100100004,800100100005,800100100006,100100100001,100100100002,100100100003,100100100004,100100100005,100100100006,100090100001,120060100001 				
   	AND 退换机标记 不包含 退机,换机,报废 				
   	AND 客户记录类型 等于 经销商,迈克,公共关系,公共关系(个人),终端客户,供应商 				
    */
	@RemoteAction
	public static Object getEquipmentMap(String tag){
			Map<String,Object> resMap = new Map<String,Object>();

		Set<String> psest = new Set<String>{'100020100002','100030500001','301532200101','301532200102','301532200103','301532200104','301532200105','301532200100',
		'300393000400','100090100002','8000303FR002','8000303RU002','800030300002','100030300001','100030300002','100040100003','100040100004','100040100005',
		'100040100006','100040100007','100040100008','100040100009','100040100010','100040100001','100040100002','100020300001','800100100003','800100100004',
		'800100100005','800100100006','100100100001','100100100002','100100100003','100100100004','100100100005','100100100006','100090100001','120060100001'};
		for(AggregateResult arg: [select count(Id) total  ,Account__r.Area__c  from Equipment__c
			where (not Account__r.Name like '%迈克测试%' ) 
			and    (Product__r.Brand__c  like: MaccuraBrandUtil.getMaccuraLikesSet() or Product__r.Brand__c  like '%加斯戴克%'  or Product__r.Brand__c  like '%深圳爱康%' )
			and Product__r.NCCode__c not in : psest 
			and (not Type__c like '%退机%')
			and (not Type__c like '%换机%')
			and (not Type__c like '%报废%')
			and Account__r.RecordType.DeveloperName in : new Set<String>{'Dealer','Maccura','TerminalCustomer','Supplier' ,'PublicRelationship','PublicRelationshipPerson'}
			group by Account__r.Area__c 
			]){
			 resMap.put(String.valueOf(arg.get('Area__c')), arg.get('total'));
		}

			System.debug(JSON.serialize(resMap));
    	 /*List <Report> reportList = [SELECT Id,DeveloperName FROM Report where
	    DeveloperName = 'TP_ZCYQ'];
		String reportId = (String)reportList.get(0).get('Id');
		Reports.reportResults results = Reports.ReportManager.runReport(reportId, true);
	
		Reports.Dimension dim = results.getGroupingsDown();

		Reports.Dimension cols = results.getGroupingsAcross();

	   for(Reports.GroupingValue groupingVal : dim.getGroupings()  ){
           
        	
           
           //子公司大区
            Reports.ReportFactWithDetails factDetails =
                (Reports.ReportFactWithDetails)results.getFactMap().get(groupingVal.getKey() + '!T');
           Object value = factDetails.getAggregates()[0].getValue();
          
          
            resMap.put(String.valueOf(groupingVal.getValue()), value);
       
       }*/
	
		//return JSON.deserializeUntyped('{"重庆征途":245,"迈克实业":921,"贵州迈克":153,"西区":134,"湖北迈克":112,"新疆迈克":40,"广东迈克":234,"山西迈克":178,"山东迈克":184,"吉林迈克":222,"云南迈克":194,"南区":125,"北区":27,"北京迈克":174,"内蒙古迈克":143,"中区":378,"上海迈可优":310}');
		return resMap;

	}

	//产培工单统计
	public static Object getWorkOrderProductMap(){
		Map<String,Map<String,Object>> wMap = new Map<String,Map<String,Object>>();
		for(AggregateResult arg :[select count(Id) total,calendar_year(CreatedDate) year ,calendar_month(CreatedDate) month from WorkOrder__c 
              where  (not ServiceManufacture__r.Account__r.Name like '%迈克测试%') 
              and  calendar_year(CreatedDate) >=:(System.today().year()-1) 
              and Status__c = '完成'
              and (Technician__r.UserDepartment__c like '%产品培训%'
              or Technician__r.UserDepartment__c like '%应用%')

              group by  calendar_year(CreatedDate),calendar_month(CreatedDate) order by calendar_year(CreatedDate)
             ]){
			String year = arg.get('year')+'年';
			Map<String ,Object> yearMap =wMap.containsKey(year) ? wMap.get(year): new Map<String,Object>();
			yearMap.put(arg.get('month')+'月',arg.get('total') );
			wMap.put(year,yearMap);
			
		}
		//System.debug(JSON.serialize(wMap));
		//return JSON.deserializeUntyped('{"2019年":{"9月":27,"8月":491,"7月":555,"6月":504,"5月":426,"4月":489,"3月":503,"2月":296,"1月":378},"2018年":{"12月":552,"11月":469,"10月":380,"9月":520,"8月":409,"7月":342,"6月":439,"5月":560,"4月":428,"3月":571,"2月":201,"1月":324}}');
		return wMap;

	}
	//工程工单统计
	public static Object getWorkOrderEnginnerMap(){
		Map<String,Map<String,Object>> wMap = new Map<String,Map<String,Object>>();
		for(AggregateResult arg :[select count(Id) total,calendar_year(CreatedDate) year ,calendar_month(CreatedDate) month from WorkOrder__c 
              where  (not ServiceManufacture__r.Account__r.Name like '%迈克测试%') 
              and  calendar_year(CreatedDate) >=:(System.today().year()-1) 
              and Status__c = '完成'
              and Technician__r.UserDepartment__c like '%工程%'
              
              group by  calendar_year(CreatedDate),calendar_month(CreatedDate) order by calendar_year(CreatedDate)
             ]){
			String year = arg.get('year')+'年';
			Map<String ,Object> yearMap =wMap.containsKey(year) ? wMap.get(year): new Map<String,Object>();
			yearMap.put(arg.get('month')+'月',arg.get('total') );
			wMap.put(year,yearMap);
			
		}
		//System.debug(JSON.serialize(wMap));
		//return JSON.deserializeUntyped('{"2019年":{"9月":555,"8月":3743,"7月":3936,"6月":3830,"5月":3618,"4月":3776,"3月":4113,"2月":2526,"1月":4060},"2018年":{"12月":3875,"11月":3899,"10月":4010,"9月":3889,"8月":3851,"7月":3615,"6月":3052,"5月":3236,"4月":2777,"3月":3649,"2月":2155,"1月":3613}}');

		return wMap;
	}	
	//获取工单总量 及同比
	@RemoteAction
	public static Map<String,Map<String,Object>> getWorkOrderTotal(String tag ){

		Map<String,Map<String,Object>> wMap = new Map<String,Map<String,Object>>();
		Map<String,Object> gcb = new Map<String,Object>();
		for(AggregateResult arg : [select count(Id) total, calendar_year(CreatedDate) year  from  WorkOrder__c  where  (not ServiceManufacture__r.Account__r.Name like '%迈克测试%') 
             
              and  calendar_year(CreatedDate) >=:(System.today().year()-1) and calendar_month(CreatedDate) <=:System.today().Month()
              and Status__c = '完成'

              and Technician__r.UserDepartment__c like '%工程%' group by  calendar_year(CreatedDate)]){
			gcb.put(arg.get('year')+'年', arg.get('total'));

		}
			wMap.put('gcb',gcb);
		Map<String,Object> cpb = new Map<String,Object>();

        for(AggregateResult arg :[select count(Id) total ,calendar_year(CreatedDate) year from  WorkOrder__c  where  (not ServiceManufacture__r.Account__r.Name like '%迈克测试%') 
           
              and  calendar_year(CreatedDate) >=:(System.today().year()-1)  and calendar_month(CreatedDate) <=:System.today().Month()
              and Status__c = '完成'

              and (Technician__r.UserDepartment__c like '%产品培训%'
             
              or Technician__r.UserDepartment__c like '%应用%') group by  calendar_year(CreatedDate)]){
			cpb.put(arg.get('year')+'年', arg.get('total'));

        }
			wMap.put('cpb',cpb);
		System.debug(JSON.serialize(wMap));

		return wMap;

	}

	//获取服务计划 完成率
	@RemoteAction
	public static Decimal getServicePlan(String tag ){
		Datetime d = Datetime.newInstance(System.now().year(),System.now().month(),1,0,0,0) ;
		Decimal total = [select count() from ServicePlan__c where Createddate >=:d];

		Decimal finish = [select count() from Case where ServicePlan__c != null 
              and  Createddate >=:d
              and (CompleteServicePlanCP__c = '按时完成' or CompleteServicePlanGC__c ='按时完成')];

        return total == 0 ? 100 : finish / total * 100 ;
	}

	@RemoteAction
	public static Object getWorkOrderTimeOut(String tag ){
		List<Object> woList = new List<Object>();
		for(WorkOrder__c wo : [select  Name ,Status__c from WorkOrder__c where 
			Createddate >=: System.now().addDays(-1)   Order by Createddate desc  limit 300 ]){
			Map<String,String> woMap = new Map<String,String>();
			woMap.put('workorder', wo.Name );
			woMap.put('status', wo.Status__c );
			woList.add(woMap);

		}
		return woList;
	}







}